//
//  CardDetailsTableViewController.swift
//  NewCard
//
//  Created by yihui on 2017/11/17.
//  Copyright © 2017年 yihui. All rights reserved.
//

import UIKit

private let hIdentifier = "hIdentifier"

class CardDetailsTableViewController: UITableViewController {

    // 数据源
    fileprivate var models : [CardModel]?
    // 统计View
    @IBOutlet weak var tabBar: UIView!
    // 总固定额度
    @IBOutlet weak var totalMoneyLabel: UILabel!
    // 总临时额度
    @IBOutlet weak var temporaryAmountMoneyLabel: UILabel!
    // 总可用额度
    @IBOutlet weak var usableAmountMoneyLabel: UILabel!
    // 总欠款金额
    @IBOutlet weak var oweMoneyLabel: UILabel!
    
    // 中间按钮
    fileprivate lazy var coreButton : UIButton = {
       
        let w : CGFloat = 300
        let h : CGFloat = 100
        let x : CGFloat = (self.view.width - w) * 0.5
        let y : CGFloat = (self.view.height - h) * 0.5
        let coreButton = UIButton(frame: CGRect(x: x, y: y, width: w, height: h))
        coreButton.setTitle("还没有银行卡请点我先添加银行卡", for: .normal)
        coreButton.layer.cornerRadius = 50
        coreButton.backgroundColor = UIColor.orange
        coreButton.addTarget(self, action: #selector(self.coreButtonClick), for: .touchUpInside)
        return coreButton
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupUI()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

// MARK: - 点击事件
extension CardDetailsTableViewController {
    
    @objc fileprivate func coreButtonClick() {
        self.performSegue(withIdentifier: "addCard", sender: nil)
    }
    
    @IBAction func colseClick(_ sender: Any) {
        
        dismiss(animated: true, completion: nil)
    }
}

//MARK: -- 生命周期方法
extension CardDetailsTableViewController {
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        tabBar.alpha = 0.0
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        loadData()
        animateTable()
    }
}

//MARK: -- 设置UI
extension CardDetailsTableViewController {
    
    fileprivate func setupUI() {
        // 不显示cell分割线
        tableView.separatorStyle = UITableViewCellSeparatorStyle.none
        // tabBar设置圆角
        tabBar.layer.cornerRadius = 10
        
        
    }
}

// MARK: - Table view delegate
extension CardDetailsTableViewController {
    
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 80
    }
    
    // MARK: -- tableView 侧滑按钮
    override func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
        
        let model = self.models?[indexPath.item]
        
        //右侧第一个按钮
        let actionOne = UITableViewRowAction(style: .normal, title: "删除") {_,_ in
            self.models!.remove(at: indexPath.item)
            // 删除数据
            if !OpenData.deleteData(data: model!) {
                //HHLog("删除失败!")
            }
            // 刷新数据
            self.loadData()
        }
        //背景颜色
        actionOne.backgroundColor = #colorLiteral(red: 0.2392156869, green: 0.6745098233, blue: 0.9686274529, alpha: 1)
        
        //右侧第二个按钮
        let actionTwo = UITableViewRowAction(style: .normal, title: "编辑") {_,_ in
            self.performSegue(withIdentifier: "edit", sender: model)
        }
        //背景颜色
        actionTwo.backgroundColor = #colorLiteral(red: 0.2745098174, green: 0.4862745106, blue: 0.1411764771, alpha: 1)
        return [actionOne, actionTwo]
    }
    
    // MARK: -- tableView 背景颜色设置
    override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        cell.backgroundColor =  colorforIndex(indexPath.row)
    }
    
    // MARK: -- tableView 背景颜色
    private func colorforIndex(_ index: Int) -> UIColor {
        
        let rowCount = models!.count <= 1 ? 1 : models!.count - 1
        let color = (CGFloat(index) / CGFloat(rowCount)) * 0.6
        return UIColor(red: 1.0, green: color, blue: 0.3, alpha: 0.8)
    }
    
    // MARK: -- tableview cell 动画
    fileprivate func animateTable() {
        let cells = tableView.visibleCells
        let tableHeight: CGFloat = tableView.bounds.size.height
        for (index, cell) in cells.enumerated() {
            cell.transform = CGAffineTransform(translationX: 0, y: tableHeight)
            UIView.animate(withDuration: 1.0, delay: 0.05 * Double(index), usingSpringWithDamping: 0.8, initialSpringVelocity: 0, options: [], animations: {
                self.tableView.alpha = 1.0
                cell.transform = CGAffineTransform(translationX: 0, y: 0);
                self.view.layoutIfNeeded()
            }, completion: { (_) in
                
                UIView.animate(withDuration: 0.5, animations: {
                    self.tabBar.alpha = 1.0
                })
            })
        }
    }
}

// MARK: - Table view data source
extension CardDetailsTableViewController {

    override func numberOfSections(in tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return models?.count ?? 0
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let model = models?[indexPath.row]
        
        let cell = tableView.dequeueReusableCell(withIdentifier: hIdentifier, for: indexPath) as! CardDetailsCell

        cell.layer.cornerRadius = 10

        cell.cardModel = model
        
        return cell
    }
    
}
// MARK: - data source
extension CardDetailsTableViewController {
    
    fileprivate func loadData() {
        
        let array = OpenData.loadData(.Card)
        var tempArr = [CardModel]()
        for arr in array! {
            
            tempArr.append(CardModel(dict:arr))
        }
        models = tempArr
        statisticsMoney(models!)
        
        if models!.count <= 0 {
            tableView.alpha = 1.0
            view.addSubview(coreButton)
        } else {
            coreButton.removeFromSuperview()
        }
        
        tableView.reloadData()
    }
    
    // 计算统计总额
    private func statisticsMoney(_ models: [CardModel]) {
        // 计算
        // 总固定额度
        var totalMoney : Double = 0
        // 总临时额度
        var temporaryAmountMoney : Double = 0
        // 总可用额度
        var usableAmountMoney : Double = 0
        // 总欠款金额
        for model in models {
            
            totalMoney += model.total
            temporaryAmountMoney += model.temporaryAmount
            usableAmountMoney += model.usableAmount
        }
        
        totalMoneyLabel.text = "总:\(Tools.calculation(totalMoney))"
        temporaryAmountMoneyLabel.text = "临:\(Tools.calculation(temporaryAmountMoney))"
        usableAmountMoneyLabel.text = "可:\(Tools.calculation(usableAmountMoney))"
        oweMoneyLabel.text = "欠:\(Tools.calculation(totalMoney - usableAmountMoney))"
    }
    
}

//MARK: -- segue跳转
extension CardDetailsTableViewController {
    
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        
        tableView.alpha = 0

        if segue.identifier == "edit" {
            
            let editCardVc = segue.destination as! CardAddModifyViewController
            editCardVc.model = sender as! CardModel
            editCardVc.isEdit = true
            return
        }
        if segue.identifier == "shopping" || segue.identifier == "repay" {
          
            let cell = (sender as! UIButton).superView(of: CardDetailsCell.self)!
            let ExpenseAddVc = segue.destination as! ExpenseAddDetailsViewController
            let ExpenseData = ExpenseModel()
            ExpenseData.id = cell.cardModel!.id
            ExpenseData.bankName = cell.cardModel!.bankName
            ExpenseData.bankCard = cell.cardModel!.bankCard
            segue.identifier == "shopping" ? (ExpenseData.useType = "消费") : (ExpenseData.useType = "还款")
            ExpenseAddVc.model = ExpenseData
            ExpenseAddVc.cardModel = cell.cardModel
            return
        }
        if segue.identifier == "expenseList" {
            
            let cell = sender as! CardDetailsCell
            let ExpenseListVC = segue.destination as! ExpenseListDetailsTableViewController
            ExpenseListVC.cardModel = cell.cardModel
            return
        }
        
    }
}
















